#include "enemy.h"
#include "map.h"
#include <QtGlobal>
#include <QTimer>


Enemy::Enemy(QPoint _pos,QPixmap enemymap)
{
    //this->setPixmap(QPixmap(":/img/fighter.bmp"));
    //this->setPos(256,200);
    this->mSpeed=1;
    this->toward=1;
    Pos=_pos;
   // _pixmap.setPixmap(enemymap);
    this->_pixmap.setPos(Pos);
    this->_pixmap.setPixmap(enemymap);
}

void Enemy::EnemyMove()
{
    srand(time(NULL));
    QPoint _dir;
    if(EnemyWall(toward))
    {
        switch(toward){
            case 1:  _dir=QPoint(0,-1);  break;
            case 2:  _dir=QPoint(0,1);  break;
            case 3:  _dir=QPoint(-1,0);  break;
            case 4:  _dir=QPoint(1,0);  break;
        default: break;
        }
        this->_pixmap.moveBy(_dir.x()*mSpeed,_dir.y()*mSpeed);
    }
    else
    {
//        while (1) {
//            int t=qrand()%4+1;
//            if(t==toward)
//        }
        while(1){
            int t=qrand()%4+1;
            if(EnemyWall(t))
            {
                toward=t;
                switch(t){
                    case 1:  _dir=QPoint(0,-1);  break;
                    case 2:  _dir=QPoint(0,1);  break;
                    case 3:  _dir=QPoint(-1,0);  break;
                    case 4:  _dir=QPoint(1,0);  break;
                default: break;
                }
                this->_pixmap.moveBy(_dir.x()*mSpeed,_dir.y()*mSpeed);
                break;
             }

        }
    }

}
//W-1,S-2,A-3,D-4
bool Enemy::EnemyWall(int tow)//敌人撞墙判定
{
    auto* themap=new Chapter1;
    int XX,YY,bo=0;
    switch(tow){
    case 1: XX=0;   YY=-1;    XX=Pos.x()+XX;   YY=Pos.y()+YY;
                    if (themap->Map[YY/20][XX/20]&&themap->Map[YY/20][XX/20+1]){bo=1;}
                    break;
    case 2: XX=0;   YY=1;     XX=Pos.x()+XX;   YY=Pos.y()+YY;
                    if (themap->Map[YY/20+1][XX/20]&&themap->Map[YY/20+1][XX/20+1]){bo=1;}
                    break;
    case 3: XX=-1;   YY=0;    XX=Pos.x()+XX;   YY=Pos.y()+YY;
                    if (themap->Map[YY/20][XX/20]&&themap->Map[YY/20+1][XX/20]){bo=1;}
                    break;
    case 4: XX=1;   YY=0;      XX=Pos.x()+XX;   YY=Pos.y()+YY;
                    if (themap->Map[YY/20][XX/20+1]&&themap->Map[YY/20+1][XX/20+1]){bo=1;}
                    break;
    default: break;
    }
    if(bo)
    {
        Pos=QPoint(XX,YY);
        return 1;
    }
    else
        return 0;
}


